package org.lex.ftp.queue;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.lex.io.BufferedStreamRedirector;
import org.lex.io.IO;
import org.lex.io.StreamRedirector;
import org.lex.progress.DefaultProgress;


/**
 * ִ��һ��Task������������ػ����ϴ�һ���ļ� ִ����һ��Task�����ͨ�� setTask( Task task )
 * ���������������
 */
public class TaskHandler extends DefaultProgress {
	private Task task = null;
	private StreamRedirector ioRedirector = null;

	public TaskHandler() {
		super();
		this.ioRedirector = new BufferedStreamRedirector(1024 * 32);
	}

	public String getStatusString() {
		if (null == this.task)
			return "";
		return task.getDescription();
	}

	public long getProgress() {
		return this.ioRedirector.getReadBytesCount();
	}

	public void abort() {
		this.ioRedirector.abort();
	}

	/**
	 * task ���ϴ�������һ���ļ���������Ŀ¼
	 * 
	 * @param task
	 */
	public void handle(Task task) throws IOException {
		this.task = task;
		this.setMaximum(task.getLength());
		this.setProgress(0L);
		this.setStartTime(System.currentTimeMillis());
		// begin io operation
		OutputStream out = task.openOutputStream();
		InputStream in = task.openInputStream();
		ioRedirector.resetCounter();
		ioRedirector.setInputStream(in);
		ioRedirector.setOutputStream(out);
		ioRedirector.call();
		IO.closeQuietly(in);
		IO.closeQuietly(out);
		task.dispose();
	}
}
